package cn.com.allunion.sms.service.mybatis.impl;

import cn.com.allunion.common.DateModule;
import cn.com.allunion.common.UUIDGenerator;
import cn.com.allunion.common.page.QueryResult;
import cn.com.allunion.sms.mapper.*;
import cn.com.allunion.sms.pojo.*;
import cn.com.allunion.sms.service.mybatis.SmsrecordService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 短信发送记录业务逻辑接口 实现类
 * Created by YangJie on 2016/4/18.
 */
@Service
@Transactional
public class SmsrecordServiceImpl implements SmsrecordService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SmsrecordServiceImpl.class) ;

    @Autowired
    UserbaseSmsbusinessMapper userbaseSmsbusinessMapper ;

    @Autowired
    SmsrecordMapper smsrecordMapper ;

    @Autowired
    SmsbusinessMapper smsbusinessMapper ;

    @Autowired
    SmsoperatorMapper smsoperatorMapper ;

    @Autowired
    DateModule dateModule ;

    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public QueryResult<Smsrecord> findByCriteria(String userId, String operatorId, Date startDate, Date endDate, String sendNumber
            , String businessId, String sendState, int pageCurrent, int pageSize) {
        UserbaseSmsbusinessExample example = new UserbaseSmsbusinessExample() ;
        UserbaseSmsbusinessExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userId) ;
        List<UserbaseSmsbusiness> usbList = userbaseSmsbusinessMapper.selectByExample(example);

        if (null != usbList && usbList.size() > 0) {
            SmsrecordExample smsrExample = new SmsrecordExample() ;
            SmsrecordExample.Criteria smsrCriteria = smsrExample.createCriteria();

            // 运营商id
            if (StringUtils.isNotBlank(operatorId)) {
                smsrCriteria.andSmsOperatorNameEqualTo(operatorId) ;
            }
            // 业务id
            if (StringUtils.isNotBlank(businessId)) {
                smsrCriteria.andBusinessRecordIdEqualTo(businessId) ;
            } else {
                List<String> businessRecordIds = new ArrayList<>(usbList.size());
                for (UserbaseSmsbusiness sbs : usbList) {
                    businessRecordIds.add(sbs.getSmsBusinessId());
                }
                smsrCriteria.andBusinessRecordIdIn(businessRecordIds) ;
            }
            // 电话号码
            if (StringUtils.isNotBlank(sendNumber)) {
                smsrCriteria.andSendNumberEqualTo(sendNumber) ;
            }
            // 状态
            if (StringUtils.isNotBlank(sendState)) {
                smsrCriteria.andSendStateEqualTo(sendState) ;
            }
            // 开始结束时间
            if (null != startDate && null != endDate) {
                smsrCriteria.andCreateDateBetween(dateModule.getDayBegin(startDate), dateModule.getDayEnd(endDate));
            }

            PageHelper.startPage(pageCurrent, pageSize) ;

            List<Smsrecord> smsrecords = smsrecordMapper.selectByExample(smsrExample);

            PageInfo<Smsrecord> pageInfo = new PageInfo<>(smsrecords) ;
            QueryResult<Smsrecord> queryResult = new QueryResult<>(smsrecords, pageInfo.getTotal()) ;

            // 处理记录，增加运营商和业务对象
            for(Smsrecord sd : queryResult.getResultList()) {
                // 设置业务对象
                sd.setSmsBusinessRecord(smsbusinessMapper.selectByPrimaryKey(sd.getBusinessRecordId()));
                // 设置运营商对象
                sd.setSmsOperator(smsoperatorMapper.selectByPrimaryKey(sd.getSmsOperatorName()));
            }

            return queryResult ;
        }

        return null;
    }

    @Override
    public String addNewRecord(Smsrecord smsRecord) {
        if (StringUtils.isBlank(smsRecord.getSmsRecordID())) {
            smsRecord.setSmsRecordID(UUIDGenerator.generatorRandomUUID());
        }
        int result = smsrecordMapper.insert(smsRecord) ;
        if (result > 0) {
            return "success";
        }

        return "failure" ;
    }

    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public List<Smsrecord> findByOperatorIdAndOperatorMessageID(String smsOperatorId, String operatorMessageID) {
        SmsrecordExample example = new SmsrecordExample();
        SmsrecordExample.Criteria criteria = example.createCriteria();
        criteria.andSmsOperatorNameEqualTo(smsOperatorId).andOperatorMessageIDEqualTo(operatorMessageID);

        return smsrecordMapper.selectByExample(example);
    }

    @Override
    public String updateOperatorMessageID(String recordID, String operatorMessageID, String states) {
        Smsrecord smsrecord = new Smsrecord() ;
        smsrecord.setSmsRecordID(recordID);
        smsrecord.setOperatorMessageID(operatorMessageID);
        smsrecord.setSendState(states);
        int result = smsrecordMapper.updateByPrimaryKeySelective(smsrecord) ;

        if (result > 0) {
            return "success";
        } else {
            return "failure" ;
        }
    }

    @Override
    public String updateSendState(String operatorMessageID, String states, String sendNumber) {
        SmsrecordExample example = new SmsrecordExample() ;
        SmsrecordExample.Criteria criteria = example.createCriteria();
        criteria.andOperatorMessageIDEqualTo(operatorMessageID);
        criteria.andSendNumberEqualTo(sendNumber);
        Smsrecord smsrecord = new Smsrecord() ;
        smsrecord.setSendState(states);
        smsrecord.setUpdateDate(new Date());
        int result = smsrecordMapper.updateByExampleSelective(smsrecord, example) ;

        if (result > 0) {
            return "success" ;
        }
        return "failure";
    }
}
